<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list" border>
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="hAssignPer(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next,total,sizes,jumper"
                :current-page="pageParams.page"
                :page-sizes="[2, 3, 5, 10]"
                :page-size="pageParams.pagesize"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        title="新增或者编辑角色"
        :visible.sync="showDialog"
        @closed="resetForm"
      >
        <el-form
          ref="roleForm"
          :model="roleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog = false">取消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="hSubmit"
            >确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限组件 -->
      <el-dialog title="分配权限" :visible.sync="perDialog">
        <assignPermission v-if="perDialog" :cur-id="curId" @success="perDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoles, addRole, updateRole, deleteRole } from '@/api/setting'
import assignPermission from './assignPermission.vue'

export default {
  components: {
    assignPermission
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      list: [], // 存储所有的角色列表
      pageParams: {
        page: 1, // 页码值
        pagesize: 2 // 每页显示的条数
      },
      total: 0, // 总条数
      showDialog: false, // 弹层
      isEdit: false, // 默认新增  ||  true 编辑
      perDialog: false, // 控制分配权限的弹层显示隐藏
      curId: '' // 接收id
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    // 获取角色列表
    async loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 当前页码
    handleCurrentChange(val) {
      console.log(`当前页:${val}`)
      // 1. 更新页码
      this.pageParams.page = val
      // 2. 重发请求
      this.loadRoles()
    },
    // 当前一页几条数据
    handleSizeChange(val) {
      console.log(`每页:${val}条`)
      this.pageParams.page = 1
      this.pageParams.pagesize = val
      // 重发请求
      this.loadRoles()
    },
    // 发送新增功能请求
    hSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (!valid) return // 检验失败
        // 检验成功发送请求
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 新增功能
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        console.log(res, 'addRole')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 重新获取数据重新渲染页面
        // 需要计算出最大的页码值
        this.total++
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        // 改变当前的页码值
        this.pageParams.page = maxPage
        // 重新获取数据渲染页面
        this.loadRoles()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    hAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    // 编辑功能
    hEdit(row) {
      console.log(row)
      this.roleForm = { ...row }
      this.isEdit = true
      this.showDialog = true
    },
    // 实现角色编辑功能
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log(res, 'addRole')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 重新获取数据渲染页面
        this.loadRoles()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    resetForm() {
      // 重置表单的检验规则和数据
      this.$refs.roleForm.resetFields()
      // 重置数据
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // 用户点击了删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 确认删除
        const res = await deleteRole(id)
        console.log(res)
        if (res.code === 10000) {
          this.$message.success(res.message)
          // 判断当前页面是否剩下一条数据
          if (this.list.length === 1) {
            this.pageParams.page--
            if (this.pageParams.page <= 0) {
              this.pageParams.page = 1
            }
          }
          // 重新渲染
          this.loadRoles()
        }
      }).catch((error) => {
        console.log(error)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    hAssignPer(id) {
      console.log(id, 'id')
      this.curId = id
      this.perDialog = true
    }
  }
}
</script>
